package com.hmall.search.listener;

import com.hmall.api.dto.ItemDTO;
import com.hmall.search.service.IItemSearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>
 * 商品数据更新监听
 * <p>
 * @author: liuhongjun
 * @since: 2024-05-18
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ItemListener {

    private final IItemSearchService searchService;

    /**
     * 监听商品新增的业务
     * @param itemDTO 商品信息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.save.queue", durable = "true"),
            exchange = @Exchange(name = "item.topic", type = ExchangeTypes.TOPIC),
            key = "item.save"
    ))
    public void listenItemSave(@Payload ItemDTO itemDTO) {
        // 捕获异常，否则出错会无限循环
        try {
            this.searchService.save(itemDTO);
        } catch (Exception e) {
            log.error("failed send message", e);
            throw new AmqpRejectAndDontRequeueException("Failed to process message", e);
        }
    }

    /**
     * 监听商品修改的业务
     * @param ids 商品id集合
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.update.queue", durable = "true"),
            exchange = @Exchange(name = "item.topic", type = ExchangeTypes.TOPIC),
            key = "item.update"
    ))
    public void listenItemUpdate(List<Long> ids) {
        this.searchService.update(ids);
    }

    /**
     * 监听商品删除的业务
     * @param id 商品id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.delete.queue", durable = "true"),
            exchange = @Exchange(name = "item.topic", type = ExchangeTypes.TOPIC),
            key = "item.delete"
    ))
    public void listenItemDelete(Long id) {
        this.searchService.delete(id);
    }
}
